<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
// 应用公共文件
use app\common\exception\ApiException;
use app\model\UserProgram;
use app\util\Feie;
use app\util\QRcode;
use app\util\ProgramQrcode;
use app\util\Juhe;
use app\util\WxProgram;
use app\util\ReturnCode;
use app\util\Tools;
use Gregwar\Captcha\CaptchaBuilder;
use think\Exception;
use think\Log;
use app\model\Agent;
use think\Db;
use think\Session;

/**
 * @param $value 需要的数据
 * @param string $key
 * @return string
 */
function getQrcode($value = [], $key = 'laikeTianDou',$type=0){
    if($type == 0){
        $arr['key'] = $key;  //二维码内容
        $arr['value'] = $value;
        $value = json_encode($arr);
    }
    $errorCorrectionLevel = 'M';    //容错级别
    $matrixPointSize = 12;          //生成图片大小
    //生成二维码图片`
    ob_start();
    QRcode::png($value,false,$errorCorrectionLevel, $matrixPointSize, 2);
    $a =  base64_encode(ob_get_contents());
	ob_end_clean();
	return  $a;
}
/**
 * 把返回的数据集转换成Tree
 * @param $list
 * @param string $pk
 * @param string $pid
 * @param string $child
 * @param string $root
 * @return array
 */
function listToTree($list, $pk='id', $pid = 'fid', $child = '_child', $root = '0') {
    $tree = array();
    if(is_array($list)) {
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] = &$list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

function formatTree($list, $lv = 0, $title = 'name'){
    $formatTree = array();
    foreach($list as $key => $val){
        $title_prefix = '';
        for( $i=0;$i<$lv;$i++ ){
            $title_prefix .= "|---";
        }
        $val['lv'] = $lv;
        $val['namePrefix'] = $lv == 0 ? '' : $title_prefix;
        $val['showName'] = $lv == 0 ? $val[$title] : $title_prefix.$val[$title];
        if(!array_key_exists('_child', $val)){
            array_push($formatTree, $val);
        }else{
            $child = $val['_child'];
            unset($val['_child']);
            array_push($formatTree, $val);
            $middle = formatTree($child, $lv+1, $title); //进行下一层递归
            $formatTree = array_merge($formatTree, $middle);
        }
    }
    return $formatTree;
}


function getLocation($mobile){
    $params = array(
        "phone" => $mobile,//需要查询的手机号码
        "key" => "b8dd0e3625369dffed4dd60cfea97024",//应用APPKEY(应用详细页查询)
    );
    $paramstring = http_build_query($params);
    $content = Juhe::Location( $paramstring);
    $result = json_decode($content, true);
    if ($result['result']) {
        return $result['result'];
    } else {
        //请求异常
        Log::write($result,'locationError');
        return false;
    }
}

function getDatestr($time){
    $date = date("y-m-d H:i:s",$time);
    $str = substr($date,9,2);
    //$str = (int)$str +1;
    $str = "TIAN".$str;
    return $str;
}

/**
 * 判断是否当前代理下级
 * @param $value 当前代理id
 *   @param $value 下级代理id
 * @return string
 */
function isSubor($agentID,$agentIDs){
    $model =  new Agent();
    $agentInfo =  $model->find($agentID);
    $agentInfos =  $model->find($agentIDs);

    // 判断是否是当前代理区域
    $adCode = '00';
    $adCodes = '00';
    if($agentInfo['type'] == '3'){
        $adCode = substr($agentInfo['adCode'],0,2);
        $adCodes = substr($agentInfos['adCode'],0,2);
    }elseif($agentInfo['type'] == '2'){
        $adCode = substr($agentInfo['adCode'],0,4);
        $adCodes = substr($agentInfos['adCode'],0,4);
    }elseif($agentInfo['type'] == '1'){
        $adCode = $agentInfo['adCode'];
        $adCodes = $agentInfos['adCode'];
    }
    if ($adCode !=  $adCodes || $agentInfos['type'] >= $agentInfo['type']){
       return false;
    }
    return true;
}

/**
 * 判断是否当前代理下级
 * @param $value 当前代理id
 *   @param $value 商家代理id
 * @return string
 */
function isSuborMaster($agentID,$masterID){
    $model =  new Agent();
    $agentInfo =  $model->find($agentID);
    $MasterInfo =  \app\model\Master::get($masterID);

    // 判断是否是当前代理区域
    $adCode = '00';
    $adCodes = '00';
    if($agentInfo['type'] == '3'){
        $adCode = substr($agentInfo['adCode'],0,2);
        $adCodes = substr($MasterInfo['adCode'],0,2);
    }elseif($agentInfo['type'] == '2'){
        $adCode = substr($agentInfo['adCode'],0,4);
        $adCodes = substr($MasterInfo['adCode'],0,4);
    }elseif($agentInfo['type'] == '1'){
        $adCode = $agentInfo['adCode'];
        $adCodes = $MasterInfo['adCode'];
    }
    if ($adCode !=  $adCodes ){
        return false;
    }
    return true;
}

/**
 * 获取当前上级
 * @param $value 当前代理id
 * @return arr
 */
function getSuper($agentID){
    $model =  new Agent();
    $agentInfo =  $model->find($agentID);
    if(empty($agentInfo)){
    	return [];
    }
    $where = [];
    if($agentInfo['type'] == '0'){
        $where['type'] = '1';
        $where['adCode'] = $agentInfo['adCode'];
    }elseif ($agentInfo['type'] == '1'){
        $where['type'] = '2';
        $str = substr($agentInfo['adCode'],0,4);
        $where['adCode'] = array('like',$str.'%');
    }elseif ($agentInfo['type'] == '2'){
        $where['type'] = '3';
        $str = substr($agentInfo['adCode'],0,2);
        $where['adCode'] = array('like',$str.'%');
    }elseif ($agentInfo['type'] == '3'){
        $where['type'] = '4';
        $where['agentID'] = $agentInfo['parentID'];
    }
    $parentInfo = $model->where($where)->find();
    if ($parentInfo){
        return $parentInfo;
    }else{
        $parentInfo =  $model->find($agentInfo['parentID']);
        if($parentInfo['type'] > $agentInfo['type']){
            return $parentInfo;
        }
    }
    return false;
}





/**
 * 获取所有上级id
 * @param $value 当前代理id
 * @return string
 */
function getSuperArr($agentID){
    $model =  new Agent();
    $where['agentID'] = $agentID;
    $str =  $model->where($where)->value('parentID');
    if(!empty($str) && $str != 0){
        $str1 = getSuperArr($str);
        if(!empty($str1)){
            return $str.','.$str1;
        }
        return $str;
    }
    return false;
}

/**
 * 获取所有上级id
 * @param $value 当前代理id
 * @return string
 */
function getRecommendArr($agentID){
    $model =  new Agent();
    $where['agentID'] = $agentID;
    $str =  $model->where($where)->value('recommendID');
    if(!empty($str) && $str != 0){
        $str1 = getRecommendArr($str);
        if(!empty($str1)){
            return $str.','.$str1;
        }
        return $str;
    }
    return false;
}

function isIPCache(){
    return true;
    $ip =  \app\util\Tools::get_client_ip();
    $count = \think\Cache::get("register".$ip);
    //$date = time();
    //$dates = date("Y-m-d",strtotime('+1 day'));
    //    $time =date( "Y-m-d H:i:s",strtotime($dates));
    //$time =strtotime($dates);
    //$dateNum = $time-$date;
    if(empty($count)){
        $num = 1;
        \think\Cache::set('register'.$ip,$num,86400);
        return false;
    }
    if(!empty($count) && $count < 5){
        $num = $count +1;
        \think\Cache::set('register'.$ip,$num,86400);
        return false;
    }
    return true;

}




function addUser($mobile){

    $user = \app\model\User::get(['mobile' => $mobile]);

    if ($user) {
        return  false;
    } else {
        //注册
        $appType = Tools::getOS();
        $get_client_ip = Tools::get_client_ip();
        $begin = strtotime('-60 day');
        $end = time();
        $time = mt_rand($begin,$end);
        $location = '{"province":"\u6c5f\u897f","city":"\u840d\u4e61","areacode":"0799","zip":"337000","company":"\u79fb\u52a8","card":""}';
        $data = [
            'appType' => $appType,
            'clientIP' => $get_client_ip,
            'status' => 1,
            'type' => 0,
            'judge' => 1,
            'mobile' => $mobile,
            'location' => $location,
            'addTime' => $time,
        ];

        Db::startTrans();
        try {
            $data['nickname'] = '添豆' . substr($mobile, 0, 3) . substr($mobile, 7);
            $userInfo = \app\model\User::create($data);

            $programData = [
                'userID' => $userInfo['userID'],
                'parentID' => 0,
                'agentID' => 0,
                'beans' => 0,
                'VIP' => 0,
                'addTime' => $time,
            ];

            $programInfo = UserProgram::create($programData);

            if ($userInfo && $programInfo) {
                Db::commit();
                return true;
            } else {
                throw new Exception('注册失败');
            }

        } catch (\Exception $e) {
            Db::rollback();
            return Tools::buildReturn(ReturnCode::LOGIN_ERROR, $e->getMessage());
        }
    }
}


function JudgeUser($num=5000,$mobilestr = '158799'){
    for($i=0; $i<$num; $i++ ){
        $str = mt_rand(10000,99999);
        $mobile = $mobilestr.$str;
        $data[] = addUser($mobile);
    }
    return $data;
}

function isAddUserCaptcha(){
    $ip =  \app\util\Tools::get_client_ip();
    $count = \think\Cache::get("addUserCaptcha".$ip);
    //$date = time();
    //$dates = date("Y-m-d",strtotime('+1 day'));
    //    $time =date( "Y-m-d H:i:s",strtotime($dates));
    //$time =strtotime($dates);
    //$dateNum = $time-$date;
    if(empty($count)){
        $num = 1;
        \think\Cache::set('addUserCaptcha'.$ip,$num,86400);
        return false;
    }
    if(!empty($count) && $count < 3){
        $num = $count +1;
        \think\Cache::set('addUserCaptcha'.$ip,$num,86400);
        return false;
    }
    return true;

}

function  getCaptcha($type='register'){
    $ip =  \app\util\Tools::get_client_ip();
    $builder = new CaptchaBuilder();
    $builder->build();
    $res1 = $builder->getPhrase();
    $codes = Session::set($type.$ip,$res1);
    $res2 = $builder->inline();
    return $res2;
}

function  ifCaptcha($code,$type='register'){
    $ip =  \app\util\Tools::get_client_ip();
    $codes = Session::get($type.$ip);
    if($code == $codes){
        Session::delete($type.$ip);
        return false;
    }
    return true;
}

function comparison($img= '',$img1=''){


    $akId = "LTAIKahSB3F4bQhk";
    $akSecret = "kHRO2XCdiPwxpyuqOFQFOyHpbvHuGJ";
    //更新api信息
    $url = "https://dtplus-cn-shanghai.data.aliyuncs.com/face/verify";
    $content = [
        'type' =>0,
        'image_url_1'=> $img,
        'image_url_2'=> $img1,
    ];
    $content = json_encode($content);
    $options = array(
        'http' => array(
            'header' => array(
                'accept'=> "application/json",
                'content-type'=> "application/json",
                'date'=> gmdate("D, d M Y H:i:s \G\M\T"),
                'authorization' => ''
            ),
            'method' => "POST", //可以是 GET, POST, DELETE, PUT
            'content' => $content //如有数据，请用json_encode()进行编码
        )
    );
    $http = $options['http'];
    $header = $http['header'];
    $urlObj = parse_url($url);
    if(empty($urlObj["query"]))
        $path = $urlObj["path"];
    else
        $path = $urlObj["path"]."?".$urlObj["query"];
    $body = $http['content'];
    if(empty($body))
        $bodymd5 = $body;
    else
        $bodymd5 = base64_encode(md5($body,true));
    $stringToSign = $http['method']."\n".$header['accept']."\n".$bodymd5."\n".$header['content-type']."\n".$header['date']."\n".$path;
    $signature = base64_encode(
        hash_hmac(
            "sha1",
            $stringToSign,
            $akSecret, true));
    $authHeader = "Dataplus "."$akId".":"."$signature";
    $options['http']['header']['authorization'] = $authHeader;
    $options['http']['header'] = implode(
        array_map(
            function($key, $val){
                return $key.":".$val."\r\n";
            },
            array_keys($options['http']['header']),
            $options['http']['header']));
    $context = stream_context_create($options);
    $file = file_get_contents($url, false, $context );
    $result = json_decode($file, true);
    if($result['errno'] == '0'){
        if($result['confidence']>= 80){
            return true;
        }
    }
    return false;
}


function isGrant($areacode,$status,$agentID='',$parentID=0){
    $isGrant = config('app.ISGRANT');
    $ISLOCATION = config('app.ISLOCATION');
    if($isGrant){
        $isIPCache = isIPCache();
        if($isIPCache){
            return   0;
        }
        if($ISLOCATION && $areacode != '0799' ){
            return 0;
        }
        if($status != 0){
            return 0;
        }
        if(!empty($agentID) && $agentID >= 1){
            return Tools::randomPrice(3, 3.1);
        }

        if(!empty($parentID) && $parentID >= 1){
            return Tools::randomPrice(3, 3.1);
        }

        return Tools::randomPrice(1, 2);
    }
    return 0;
}
function getExpress($deliveryType,$deliveryTradeNo,$orderInfo='',$type = 0){
    if(empty($orderInfo)){
        return false;
    }
    if(!empty($orderInfo) && $orderInfo['deliveryTime'] !=0 && $type != 0){
        if($orderInfo['deliveryStatus'] == 1 ){
            return $orderInfo['deliveryContent'];
        }
        if(date("y-m-d",$orderInfo['deliveryTime']) == date("y-m-d")){
            return $orderInfo['deliveryContent'];
        }
    }
    $orderInfo->deliveryTime= time();
    $EBusinessID = config('kuaidiniao.EBusinessID');
    $AppKey = config('kuaidiniao.AppKey');
    $url = "http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";
    $requestData= "{'OrderCode':'','ShipperCode':'".$deliveryType."','LogisticCode':'".$deliveryTradeNo."'}";
    $datas = array(
        'EBusinessID' => $EBusinessID,
        'RequestType' => '1002',
        'RequestData' => urlencode($requestData) ,
        'DataType' => '2',
    );
    $datas['DataSign'] = urlencode(base64_encode(md5($requestData.$AppKey)));
    $model = new Juhe();
    $result= $model->sendPost($url, $datas);
    $result = json_decode($result);
    $arr = [];
    if($result->Success){
        $where['LogisticCode'] = $deliveryType;
        $experssInfo = \app\model\Express::get($where);
        $arr['deliveryType'] = $experssInfo['ShipperCode'];
        $arr['deliveryTradeNo'] = $deliveryTradeNo;
        $arr['Traces'] = $result->Traces;
        if($result->Traces == 3 || $result->Traces == 4){
            $orderInfo->deliveryStatus = 1;
        }
        $status = ['0'=>'揽收中','1'=>'已揽收','2'=>'在途中','3'=>'已完成','4'=>'问题件'];
        $arr['statusText'] = $status[$result->State];
        $orderInfo->deliveryContent = json_encode($arr,true);

    }else{
        //请求异常
        log::write($result,'experssError');
    }
    $orderInfo->save();
    return $arr;
}

function figure($tradeNo){
    $where['tradeNo'] = $tradeNo;
    $orderModel = new \app\model\ScOrder();
    $orderInfo = $orderModel->alias('o')
        ->join('master m','m.masterID = o.masterID','left')
        ->join("userAddress a",'a.addressID = o.addressID','left')
        ->field('o.tradeNo,m.cityName,m.address as masterAddress,a.region,a.address,a.latitude,a.longitude,m.latitude as masterlatitude,m.longitude as masterlongitude')
        ->where($where)
        ->find();
    if(empty($orderInfo)){
        return false;
    }
    if($orderInfo['weight'] > 20000){
        throw new ApiException('超出配送重量,请拒绝接单', 200,ReturnCode::INVALID);
    }
    if($orderInfo[''])
    $model = new Juhe();
    $result= $model->uuPrice($orderInfo);
    $distance = config('uu.distance');
    if(!isset($result) ||$result['distance'] == $distance){
        throw new ApiException('超出配送距离,请拒绝接单', 200,ReturnCode::INVALID);
    }else{
        $orderInfo->deliveryContent = json_encode($result);
        $orderInfo->save();
    }
    return $result;
}

function addUUorder($tradeNo){
    $where['tradeNo'] = $tradeNo;
    $orderModel = new \app\model\ScOrder();
    $orderInfo = $orderModel->alias('o')
        ->join('master m','m.masterID = o.masterID','left')
        ->join("userAddress a",'a.addressID = o.addressID','left')
        ->field('o.tradeNo,o.deliveryContent,a.consignee,a.mobile,a.mobile,m.mobile as masterMobile')
        ->where($where)
        ->find();
    $model = new Juhe();
    $result= $model->addUuOrder($orderInfo);
    if(!isset($result) ){
        return false;
    }else{
        $orderInfo->deliveryTradeNo = $result;
        $orderInfo->save();
    }
    return $result;
}

function cancel($tradeNo){
    $where['tradeNo'] = $tradeNo;
    $orderModel = new \app\model\ScOrder();
    $orderInfo = $orderModel->alias('o')
        ->join('master m','m.masterID = o.masterID','left')
        ->join("userAddress a",'a.addressID = o.addressID','left')
        ->field('o.tradeNo,o.deliveryTradeNo')
        ->where($where)
        ->find();
    $model = new Juhe();
    $result= $model->cancel($orderInfo);
    if(!isset($result) ){
        return false;
    }else{
        $orderInfo->deliveryContent = '';
        $orderInfo->deliveryTradeNo = '';
        $orderInfo->save();
    }
    return $result;
}

    /*
        $total_money:红包总金额
        $total_people:总人数/总分数
        $min_money:每份红包的最小金额
        $max_money:每份红包的最大金额
    */
    function redpack($money, $count, $min, $max,$packetID=0,$articleID=0)
    {
        if($packetID == 0){
            return false;
        }
        $money  = Tools::bcCalculate($money,100,"*");
        $min  = Tools::bcCalculate($min,100,"*");
        $max  = Tools::bcCalculate($max,100,"*");
        $ret = array();
        $new_ret = array();
        $total_real_money = $money - $count * $min; // 最高可分配金额
        $ret[0] = 0;
        for ($i = 1; $i < $count; $i++) {
            $ret[$i] = get_rand($ret[$i - 1], $total_real_money, ($max - $min));
        }

        $amount = 0;
        sort($ret);
        for ($j = 0; $j < count($ret); $j++) {
            $new_ret[$j]['packetID'] =  $packetID;
            $new_ret[$j]['articleID'] =  $articleID;
            if ($j == count($ret) - 1) {
                if($money-$amount > $max){
                    $amount += $max;
                    $new_ret[count($ret) - 1]['money'] = $max;
                    $sum = $money-$amount;
                     return get_rands($new_ret,$sum,$min,$max);
                }else{
                    $new_ret[count($ret) - 1]['money'] = $money-$amount;
                }
            } else {
                $new_ret[$j]['money'] = ($ret[$j + 1] - $ret[$j] + $min) ;
                $amount += ($ret[$j + 1] - $ret[$j] + $min) ;
            }
        }
        shuffle($new_ret);
        return $new_ret;
    }


    function get_rand($start, $end, $max){
        $maxmoney = $max + $start < $end ? $max + $start : $end ;
        $tmp = rand($start, $maxmoney);
        if ($tmp > $max + $start || empty($tmp)) {
            return get_rand($start, $end, $max);
        } else {
            return $tmp;
        }
    }

    function get_rands($arr,$sum,$min,$max){
        $average = ($max-$min)/2;
        $average = intval($average);
        $money = rand($min, $average);
        $amount = 0;
        foreach ($arr as $k=>$v){
            if($sum > 0 && $average >$v['money']){
                $money = $money > $sum ? $sum : $money;
                $arr[$k]['money'] = $v['money'] + $money;
                $sum -= $money;
            }
            $amount += $v['money'];
       }
        return $arr;
    }

    function getWxUserInfo($encryptedData,$iv,$sessionKey,$type = 1){
        $appid = config('program.AppID');
        if($type != 1){
            $appid = config('program.masterAppID');
        }


        $pc = new WxProgram($appid, $sessionKey);
        $data = [];
        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0) {
            return  json_decode($data,true);
        } else {
            return $errCode;
        }
    }

    /**
     * 创建随机数
     * @param $length
     * @param string $base
     */
    function getRandom($length=12,$base="1234567890abcdefghijklmnopqrstuvwxyz"){
        $len = strlen($base)-1;
        $str = "";
        for($i=0;$i<$length;$i++){
            $str .= $base[rand(0,$len)];
        }
        return $str;
    }

    function getStorageFreight($Money) {
        $arr = config('apiAdmin.STIRAGE_FREIGHT');
        $num  = 0 ;
        foreach ($arr as $k => $val){
            if($Money >= $val ){
                $num = $k;
            }
        }
        return $num;
    }

    function getCompanyFreight($Money) {
        $arr = config('apiAdmin.COMPANY_STIRAGE_FREIGHT');
        $num  = 0 ;
        foreach ($arr as $k => $val){
            if($Money >= $k ){
                $num = $val;
            }
        }
        return $num;
    }

    function format_date($time){
        $t=time()-$time;
        if($t > 1800){
            return date("Y-m-d",$time);
        }
        $f=array(
            '31536000'=>'年',
            '2592000'=>'个月',
            '604800'=>'星期',
            '86400'=>'天',
            '3600'=>'小时',
            '60'=>'分钟',
            '1'=>'秒'
        );
        foreach ($f as $k=>$v)    {
            if (0 !=$c=floor($t/(int)$k)) {
                return $c.$v.'前';
            }
        }
    }

    /*
     * 数量
     * 金额
     * 批次 两位数
     * 年份 年份最后一位  带月份 三位数
     */
    function generateRefill($num=100,$batch = 01,$ym = '001' ){
        set_time_limit(0);

        //处理缓冲区
        ob_end_clean();
        ob_implicit_flush(true);

        if($num==0) return;
        if($ym == '001'){
            $ym = date("md");
            $ym = substr($ym,1,3);
        }
        $arr = [];
        $num = $num + 111;
        for($i=111;$i<$num;$i++)
        {
            $sn=sprintf("%02s%s%0s",$batch,$ym,$i);
            $seek=mt_rand(0,9999).mt_rand(0,9999).mt_rand(0,9999); //12位
            $start=mt_rand(0,20);
            $str=strtoupper(substr(md5($seek),$start,8));
            $str=str_replace("O",chr(mt_rand(65,78)),$str);
            $str=str_replace("0",chr(mt_rand(65,78)),$str);
            $str = $sn.$str;
            if(in_array($str,$arr)){
                $i--;
            }else{
                $arr[] = $str;
            }
        }
        return $arr;
    } //函数结束

function getProgramQrcode($path,$userID,$productID=0){
    $pc = new ProgramQrcode();
    $str = 'u='.$userID;
    $color = ['r'=>'255','g'=>'255','b'=>'255'];
    if($productID!= 0){
        $str = $str.'&m='.$productID;
        $color  = [];
    }
    $Qrcode = $pc->mpcode($path, $str,$color);
    return $Qrcode;
}

function getOrderNum(){
    $date = date("Y-m-d");
    $count = \think\Cache::get("reachOrderCount".$date);
    if(empty($count)){
        $num = 1;
        \think\Cache::set('reachOrderCount'.$date,$num,86400);
    }else{
        $num = $count +1;
        \think\Cache::set('reachOrderCount'.$date,$num,86400);
    }
    return $num;
}

function verificodeHandle($str){
    //通过正则，第一位字母与之后每四位截取到数组中
    preg_match('/([a-zA-Z]{1})([\d]{4})([\d]{4})([\d]{0,})?/', $str, $match);
    $str = '';
    unset($match[0]); //去除掉第一个键
    //通过循环，将字符串进行拼接并加入空格
    foreach ($match as $vo) {
        $str .= $vo . ' ';
    }
    return $str;
}

function getMoneyOff($Money) {
    $arr = config('apiAdmin.MONEY_OFF');
    $num  = 0 ;
    foreach ($arr as $k => $val){
        if($Money >= $k ){
            $num = $val;
        }
    }
    return $num;
}

function nodeTree($arr, $id = 0, $level = 0,$idName = 'classID') {
    $list =array();
    foreach ($arr as $k=>$v){
        if ($v['parentID'] == $id){
            $v['level']= $level;
            $v['children'] = nodeTree($arr,$v[$idName],$level+1,$idName);
            $list[] = $v;
        }
    }
    return $list;
}


function refundDecrypt($str,$key) {
    $decrypt = base64_decode($str,true);
    $key = md5($key);
    return openssl_decrypt($decrypt , 'aes-256-ecb',$key, OPENSSL_RAW_DATA);
}

function ifpay(){
    $num = date('G');
    $startTime = '2';
    $overTime = '23';
    if($num >= $overTime || $num < $startTime){
        return ['startTime'=>$startTime,'overTime'=>$overTime];
    }
    return false;
}

function companyFeietest($arr,$A,$B,$C,$D,$order,$type = 0,$agentName = '')
{
    $orderInfo = '<BR>';
    $orderInfo .= '<BR>';
    $orderInfo .= '<BR>';
    $orderInfo .= '<BR>';
    $orderInfo .= '<CB>添豆企业版</CB><BR>';
    $orderInfo .= '<C>#--'.$order['orderName'].'--#</C><BR>';
    $orderInfo .= '<C>#'.$order['tradeNo'].'#</C><BR>';
    $orderInfo .= '名称           单价  数量 金额<BR>';
    $orderInfo .= '--------------------------------<BR>';
    foreach ($arr as $k5 => $v5) {
        $name = $v5['productName'];
        $price = $v5['salePrice'];
        $num = $v5['count'];
        $prices = $v5['salePrice']*$v5['count'];
        $kw3 = '';
        $kw1 = '';
        $kw2 = '';
        $kw4 = '';
        $str = $name;
        $blankNum = $A;//名称控制为14个字节
        $lan = mb_strlen($str,'utf-8');
        $m = 0;
        $j=1;
        $blankNum++;
        $result = array();
        if(strlen($price) < $B){
            $k1 = $B - strlen($price);
            for($q=0;$q<$k1;$q++){
                $kw1 .= ' ';
            }
            $price = $price.$kw1;
        }
        if(strlen($num) < $C){
            $k2 = $C - strlen($num);
            for($q=0;$q<$k2;$q++){
                $kw2 .= ' ';
            }
            $num = $num.$kw2;
        }
        if(strlen($prices) < $D){
            $k3 = $D - strlen($prices);
            for($q=0;$q<$k3;$q++){
                $kw4 .= ' ';
            }
            $prices = $prices.$kw4;
        }
        for ($i=0;$i<$lan;$i++){
            $new = mb_substr($str,$m,$j,'utf-8');
            $j++;
            if(mb_strwidth($new,'utf-8')<$blankNum) {
                if($m+$j>$lan) {
                    $m = $m+$j;
                    $tail = $new;
                    $lenght = iconv("UTF-8", "GBK//IGNORE", $new);
                    $k = $A - strlen($lenght);
                    for($q=0;$q<$k;$q++){
                        $kw3 .= ' ';
                    }
                    if($m==$j){
                        $tail .= $kw3.' '.$price.' '.$num.' '.$prices;
                    }else{
                        $tail .= $kw3.'<BR>';
                    }
                    break;
                }else{
                    $next_new = mb_substr($str,$m,$j,'utf-8');
                    if(mb_strwidth($next_new,'utf-8')<$blankNum) continue;
                    else{
                        $m = $i+1;
                        $result[] = $new;
                        $j=1;
                    }
                }
            }
        }
        $head = '';
        foreach ($result as $key=>$value) {
            if($key < 1){
                $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value);
                $v_lenght = strlen($v_lenght);
                if($v_lenght == 13) $value = $value." ";
                $head .= $value.' '.$price.' '.$num.' '.$prices;
            }else{
                $head .= $value.'<BR>';
            }
        }
        $orderInfo .= $head.$tail;
        $orderInfo .= '--------------------------------<BR>';
        @$nums += $prices;
    }
//        $orderInfo .= '--------------------------------<BR>';
    $orderInfo .= '合计：'.$order['amount'].'<BR>';
    $orderInfo .= '--------------------------------<BR>';
    $orderInfo .= '订单备注:'.$order['content'].'<BR>';
    $orderInfo .= '--------------------------------<BR>';
    $orderInfo .= '<BOLD><B>联系电话：'.'('.$order['addressContent']['consignee'].')'.$order['addressContent']['mobile'].'</B></BOLD><BR>';
    $orderInfo .= '<BOLD><B>收货门店：'.$order['addressContent']['consignee'].'</B></BOLD><BR>';
    $orderInfo .= '<BOLD><B>收货地址：'.$order['addressContent']['address'].'('.$agentName.')'.'</B></BOLD><BR>';
    $orderInfo .= '下单时间：'.$order['payTime'].'<BR>';
    $orderInfo .= '<BR>';
    $orderInfo .= '<BR>';
    $orderInfo .= '<BR>';
    $orderInfo .= '<BR>';
    if($type != 0){
        $orderInfo .= '<BR>';
        $orderInfo .= '<BR>';
        $orderInfo .= '<BR>';
        $orderInfo .= '<BR>';
        $orderInfo .= '<BR>';
        $orderInfo .= '<BR>';
        $orderInfo .= '<CB>--------------------------------<CB><BR>';
    }
    //    $orderInfo .= '备注：加辣<BR><BR>';
    //    $orderInfo .= '<QR>http://www.feieyun.com</QR>';//把解析后的二维码生成的字符串用标签套上即可自动生成二维码
    return $orderInfo;
}

function Feietest($arr,$A,$B,$C,$D,$order,$type = 0)
{

    $orderInfo = '<BR>';
    $orderInfo .= '<BR>';
    $orderInfo .= '<BR>';
    $orderInfo .= '<BR>';
    $orderInfo .= '<CB>添豆'.$order['orderNum'].'</CB><BR>';
    $orderInfo .= '<C>#--'.$order['orderName'].'--#</C><BR>';
    $orderInfo .= '<C>#'.$order['tradeNo'].'#</C><BR>';
    $orderInfo .= '名称           单价  数量 金额<BR>';
    $orderInfo .= '--------------------------------<BR>';
    foreach ($arr as $k5 => $v5) {
        $name = $v5['productName'];
        $price = $v5['salePrice'];
        $num = $v5['count'];
        $prices = $v5['salePrice']*$v5['count'];
        $kw3 = '';
        $kw1 = '';
        $kw2 = '';
        $kw4 = '';
        $str = $name;
        $blankNum = $A;//名称控制为14个字节
        $lan = mb_strlen($str,'utf-8');
        $m = 0;
        $j=1;
        $blankNum++;
        $result = array();
        if(strlen($price) < $B){
            $k1 = $B - strlen($price);
            for($q=0;$q<$k1;$q++){
                $kw1 .= ' ';
            }
            $price = $price.$kw1;
        }
        if(strlen($num) < $C){
            $k2 = $C - strlen($num);
            for($q=0;$q<$k2;$q++){
                $kw2 .= ' ';
            }
            $num = $num.$kw2;
        }
        if(strlen($prices) < $D){
            $k3 = $D - strlen($prices);
            for($q=0;$q<$k3;$q++){
                $kw4 .= ' ';
            }
            $prices = $prices.$kw4;
        }
        for ($i=0;$i<$lan;$i++){
            $new = mb_substr($str,$m,$j,'utf-8');
            $j++;
            if(mb_strwidth($new,'utf-8')<$blankNum) {
                if($m+$j>$lan) {
                    $m = $m+$j;
                    $tail = $new;
                    $lenght = iconv("UTF-8", "GBK//IGNORE", $new);
                    $k = $A - strlen($lenght);
                    for($q=0;$q<$k;$q++){
                        $kw3 .= ' ';
                    }
                    if($m==$j){
                        $tail .= $kw3.' '.$price.' '.$num.' '.$prices;
                    }else{
                        $tail .= $kw3.'<BR>';
                    }
                    break;
                }else{
                    $next_new = mb_substr($str,$m,$j,'utf-8');
                    if(mb_strwidth($next_new,'utf-8')<$blankNum) continue;
                    else{
                        $m = $i+1;
                        $result[] = $new;
                        $j=1;
                    }
                }
            }
        }
        $head = '';
        foreach ($result as $key=>$value) {
            if($key < 1){
                $v_lenght = iconv("UTF-8", "GBK//IGNORE", $value);
                $v_lenght = strlen($v_lenght);
                if($v_lenght == 13) $value = $value." ";
                $head .= $value.' '.$price.' '.$num.' '.$prices;
            }else{
                $head .= $value.'<BR>';
            }
        }
        $orderInfo .= $head.$tail;
        $orderInfo .= '--------------------------------<BR>';
        @$nums += $prices;
    }
//        $orderInfo .= '--------------------------------<BR>';
    $orderInfo .= '合计：'.$order['amount'].'<BR>';
    $orderInfo .= '--------------------------------<BR>';
    $orderInfo .= '订单备注:'.$order['content'].'<BR>';
    $orderInfo .= '--------------------------------<BR>';
    $orderInfo .= '<BOLD><B>联系电话：'.'('.$order['takeName'].')'.$order['takeMobile'].'</B></BOLD><BR>';
    if(!empty($order['master']['areaID'])){
        $agentmodel = new \app\model\Agents();
        $agent = $agentmodel->where(['agentID'=>$order['master']['areaID']])->find();
        $orderInfo .= '<BOLD><B>收货门店：'.$order['masterName'].'('.$agent['agentName'].')'.'</B></BOLD><BR>';
    }elseif(!empty($order['master']['area'])){
        $orderInfo .= '<BOLD><B>收货门店：'.$order['masterName'].'('.$order['master']['area'].')'.'</B></BOLD><BR>';
    }else{
        $orderInfo .= '<BOLD><B>收货门店：'.$order['masterName'].'</B></BOLD><BR>';
    }
    $orderInfo .= '<BOLD><B>收货地址：'.$order['master']['address'].'</B></BOLD><BR>';
    $orderInfo .= '下单时间：'.$order['payTime'].'<BR>';
    $orderInfo .= '<BR>';
    $orderInfo .= '<BR>';
    $orderInfo .= '<BR>';
    $orderInfo .= '<BR>';
    if($type != 0){
        $orderInfo .= '<BR>';
        $orderInfo .= '<BR>';
        $orderInfo .= '<BR>';
        $orderInfo .= '<BR>';
        $orderInfo .= '<BR>';
        $orderInfo .= '<BR>';
        $orderInfo .= '<CB>--------------------------------<CB><BR>';
    }
    //    $orderInfo .= '备注：加辣<BR><BR>';
    //    $orderInfo .= '<QR>http://www.feieyun.com</QR>';//把解析后的二维码生成的字符串用标签套上即可自动生成二维码
    return $orderInfo;
}

//生成签名
function signature($time){
    $user = config('feie.USER');
    $UKEY = config('feie.UKEY');
    return sha1($user.$UKEY.$time);//公共参数，请求公钥
}

/*
   *  方法1
   拼凑订单内容时可参考如下格式
   根据打印纸张的宽度，自行调整内容的格式，可参考下面的样例格式
   */
function wp_print($printer_sn,$orderInfo,$times){
    $time = time();			    //请求时间
    $user = config('feie.USER');
    $content = array(
        'user'=>$user,
        'stime'=>$time,
        'sig'=>signature($time),
        'apiname'=>'Open_printMsg',

        'sn'=>$printer_sn,
        'content'=>$orderInfo,
        'times'=>$times//打印次数
    );

    $client = new Feie('api.feieyun.cn',80);
    if(!$client->post('/Api/Open/',$content)){
        return  false;
    }
    else{
        $ret = $client->getContent();
        //服务器返回的JSON字符串，建议要当做日志记录起来
        Log::write($ret,'feieError');
        $ret = json_decode($ret,true);
        if($ret['ret'] == '0'){
            return $ret['data'];
        }
    }

}

function lockSubmit($key){
    $cache = \think\Cache::store('redis')->get($key);
    if($cache){
        return true;
    }else{
        \think\Cache::store('redis')->set($key, 1, 5);
        return false;
    }
}

function mobileDeal($phone){
    $p = substr($phone,0,3)."****".substr($phone,7,4);
    return $p;
}

function getPrizeStatus(){
    $end_time  = config('activity.prize_end_time');
    $start_time  = config('activity.prize_start_time');
    $date_now = date('Y-m-d H:i:s');
    if($date_now<$end_time && $date_now>$start_time){
        return true;
    }else{
        return false;
    }
}

function getRefundOpen(){
    $start_time = '2020-09-25 00:00:00';
    $end_time = '2020-10-01 00:00:00';
    $now = date('Y-m-d H:i:s');
    if($now>=$start_time && $now<$end_time){
        return true;
    }else{
        return false;
    }
}

function getConfigValue($name){
    $data = Db::name('config')->where('name', $name)->find();
    if(isset($data['id'])){
        return  $data['value'];
    }else{
        return false;
    }
}

function getFreshConfigValue($name){
    $data = Db::name('fresh_config')->where('name', $name)->find();
    if(isset($data['id'])){
        return  $data['value'];
    }else{
        return false;
    }
}

function emoji_encode($str)
{
    $strEncode = '';

    $length = mb_strlen($str, 'utf-8');

    for ($i = 0; $i < $length; $i++) {
        $_tmpStr = mb_substr($str, $i, 1, 'utf-8');
        if (strlen($_tmpStr) >= 4) {
            $strEncode .= '[[EMOJI:' . rawurlencode($_tmpStr) . ']]';
        } else {
            $strEncode .= $_tmpStr;
        }
    }

    return $strEncode;
}

function emoji_decode($str)
{
    $strDecode = preg_replace_callback('|\[\[EMOJI:(.*?)\]\]|', function ($matches) {
        return rawurldecode($matches[1]);
    }, $str);
    return $strDecode;
}


/*
*功能：php完美实现下载远程图片保存到本地
*参数：文件url,保存文件目录,保存文件名称，使用的下载方式
*当保存文件名称为空时则使用远程文件原来的名称
*/
function getImage($url,$save_dir='',$filename='',$type=0){
    if(trim($url)==''){
        return array('file_name'=>'','save_path'=>'','error'=>1);
    }
    if(trim($save_dir)==''){
        $save_dir='./';
    }
    if(trim($filename)==''){//保存文件名
        $ext=strrchr($url,'.');
        if($ext!='.gif'&&$ext!='.jpg'){
            return array('file_name'=>'','save_path'=>'','error'=>3);
        }
        $filename=time().$ext;
    }
    if(0!==strrpos($save_dir,'/')){
        $save_dir.='/';
    }
    //创建保存目录
    if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
        return array('file_name'=>'','save_path'=>'','error'=>5);
    }
    //获取远程文件所采用的方法
    if($type){
        $ch=curl_init();
        $timeout=5;
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
        $img=curl_exec($ch);
        curl_close($ch);
    }else{
        ob_start();
        readfile($url);
        $img=ob_get_contents();
        ob_end_clean();
    }
    //$size=strlen($img);
    //文件大小
    $fp2=@fopen($save_dir.$filename,'a');
    fwrite($fp2,$img);
    fclose($fp2);
    unset($img,$url);
    return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
}

function getVipStatus($userID){
    $user_program = Db::name('user_program')->where('userID', $userID)->find();
    if($user_program['yearVip'] == 0){
        $status = 0;
    }else{
        if($user_program['yearVipExpireTime']> time()){
            $status = 1;
        }else{
            $status = -1;
        }
    }
    return $status;
}

function convertUrlQuery($query) {

    $queryParts = explode('&', $query);
    $params = array();
    foreach ($queryParts as $param) {
        $item = explode('=', $param);
        $params[$item[0]] = $item[1];
    }

    return $params;
}

function getUrlQuery($array_query)
{
    $tmp = array();
    foreach ($array_query as $k => $param) {
        $tmp[] = $k . '=' . $param;
    }
    $params = implode('&', $tmp);
    return $params;
}


/**
 * 随机字符
 * @param number $length 长度
 * @param string $type 类型
 * @param number $convert 转换大小写
 * @return string
 */
function random($length=6, $type='string', $convert=0){
    $config = array(
        'number'=>'1234567890',
        'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#%*&@'
    );

    if(!isset($config[$type])) $type = 'string';
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) -1;
    for($i = 0; $i < $length; $i++){
        $code .= $string{mt_rand(0, $strlen)};
    }
    if(!empty($convert)){
        $code = ($convert > 0)? strtoupper($code) : strtolower($code);
    }
    return $code;
}
